from typing import Union
from fastapi import FastAPI, Depends, Request, Response
from pydantic import BaseModel
from fastapi import APIRouter
import logging
import asyncio
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

from starlette.exceptions import HTTPException as StarletteHTTPException

# from app.api.router import router
from app.common.common import returnData


from novelapp.api.router import novel_router
from novelapp.utils.scheduler_tasks import daily_sync_youshudan
from novelapp.common.common import returnData as novelReturnData

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


app = FastAPI()

# 创建定时任务调度器
scheduler = AsyncIOScheduler()

# 添加定时任务：每天凌晨0点执行
scheduler.add_job(
    daily_sync_youshudan,
    trigger=CronTrigger(hour=0, minute=0),  # 每天0点执行
    id='daily_sync_youshudan',
    name='每日同步优书单',
    replace_existing=True
)

# 启动事件：启动定时任务调度器
@app.on_event("startup")
async def startup_event():
    scheduler.start()
    logging.info("定时任务调度器已启动")
    logging.info("每日优书单同步任务已配置: 每天 00:00 执行")

# 关闭事件：停止定时任务调度器
@app.on_event("shutdown")
async def shutdown_event():
    scheduler.shutdown()
    logging.info("定时任务调度器已停止")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

# 异常转换中间件
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content=returnData(exc.status_code, exc.detail, None)
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=returnData(status.HTTP_422_UNPROCESSABLE_ENTITY, "Validation error", None)
    )



# 初始化 MongoUtils 实例
# def get_mongo_utils_instance():
#     return MongoUtils(mongo_config)

# app.include_router(router, prefix='/v1')

app.include_router(novel_router, prefix='/nv1')
# 挂载静态文件目录
app.mount("/output", StaticFiles(directory="output/figures"), name="output")

@app.get("/api/healthchecker")
def root():
    return {"message": "Welcome to FastAPI with MongoDB"}


@app.post("/api/manual_sync_youshudan")
async def manual_sync_youshudan():
    """
    手动触发优书单同步任务
    
    该接口会立即执行优书单列表和书籍信息的同步
    """
    logging.info("收到手动同步优书单请求")
    
    try:
        # 在后台异步执行同步任务
        result = await daily_sync_youshudan()
        
        return novelReturnData(200, '同步任务已完成', result)
        
    except Exception as e:
        logging.error(f"手动同步失败: {str(e)}")
        return novelReturnData(500, f'同步失败: {str(e)}', None)


@app.get("/api/scheduler_status")
def get_scheduler_status():
    """
    获取定时任务调度器状态
    """
    jobs = []
    for job in scheduler.get_jobs():
        jobs.append({
            "id": job.id,
            "name": job.name,
            "next_run_time": str(job.next_run_time) if job.next_run_time else None,
            "trigger": str(job.trigger)
        })
    
    return novelReturnData(200, '获取调度器状态成功', {
        "running": scheduler.running,
        "jobs": jobs
    })
